<template>
  <div class="map-exchange-bg">
    <el-card class="map-bg">
      <div id="dividerMap"></div>
      <div class="map-operate" v-if="drawFlag">
        <el-tooltip v-if="drawState == '1'" class="item" effect="dark" content="区域绘制" placement="top">
          <el-button class="map-operate-icon" type="text" icon="el-icon-share" circle @click="drawStart"></el-button>
        </el-tooltip>
        <template v-if="drawState == '2'">
          <!-- <i class="el-icon-top-left"></i>
          <span> | </span>
          <i class="el-icon-top-right"></i>
          <span> | </span> -->
          <el-tooltip class="item" effect="dark" content="绘制清空" placement="top">
            <el-button class="map-operate-del-icon" type="text" icon="el-icon-close" circle @click="drawCancel"></el-button>
          </el-tooltip>
          <span> | </span>
          <el-tooltip class="item" effect="dark" content="绘制完成" placement="top">
            <el-button class="map-operate-ok-icon" type="text" icon="el-icon-check" circle @click="drawSave"></el-button>
          </el-tooltip>
        </template>
      </div>
    </el-card>
    <div class="operate-bg">
      <!-- 分单范围 -->
      <el-card>
        <div slot="header" class="page-title-bg">
          <div class="page-title">
            <div class="title-icon"></div>
            <span>分单范围</span>
          </div>
        </div>
        <div>
          <el-form ref="rangeForm" v-model="rangeForm">
            <el-form-item label="三级机构：" prop="manageCom">
              <el-input v-model="rangeForm.manageCom" :disabled="true" style="width: 70%;"></el-input>
            </el-form-item>
            <el-form-item label="行政区域：" prop="company">
              <el-select v-model="rangeForm.company" placeholder="请选择三级机构下辖行区域" style="width: 70%;">
                <el-option v-for="item in companyList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item style="text-align: right;">
              <!-- <el-button size="mini">重置</el-button> -->
              <el-button type="primary" size="mini" @click="saveRange">确定范围</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      <!-- 分单区域 -->
      <el-card style="margin-top: 20px;">
        <div slot="header" class="page-title-bg">
          <div class="page-title">
            <div class="title-icon"></div>
            <span>分单区域</span>
          </div>
        </div>
        <el-table :data="policyMapList" height="calc(100vh - 500px)" style="width: 100%;">
          <el-table-column prop="number" label="序号" align="center" width="50"></el-table-column>
          <el-table-column prop="areaName" label="分单区域名称" align="center"></el-table-column>
          <el-table-column prop="placeName" label="行政区域" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scoped">
              <el-button type="text" size="mini" @click="delPolicyMap(scoped.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="float: right; margin: 20px 0;">
          <el-button type="primary" size="mini" @click="goBack">上一步</el-button>
          <el-button type="primary" size="mini" @click="nextOperateFn">下一步</el-button>
        </div>
      </el-card>
    </div>
    <el-dialog title="提示" :visible.sync="drawSaveVisible" width="520px" :show-close="false">
      <span>
        您已绘制一块闭合区域，是否生成“
        <el-input v-model="drawName" placeholder="请输入闭合区域名称" style="width: 200px;" />
        ”分单区域?
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDrawFn('1')">取 消</el-button>
        <el-button type="primary" @click="saveDrawFn()" :disabled="!drawName">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="drawAutoVisible" width="520px" :show-close="false">
      <span>
        您有多个行政区域未划分，是否全部自动生成分单区域？
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDrawFn('2')">取 消</el-button>
        <el-button type="primary" @click="drawNextFn()" :disabled="!drawName">确 定</el-button>
      </span>
    </el-dialog>
    <!-- <el-dialog title="提示" :visible.sync="drawNextVisible" width="520px" :show-close="false">
      <span>
        您有一处空白区未划分，是否自动生成“
        <el-input v-model="drawNormalName" placeholder="请输入闭合区域名称" style="width: 200px;" />
        ”分单区域?
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDrawFn('3')">取 消</el-button>
        <el-button type="primary" @click="drawNextFn()" :disabled="!drawName">确 定</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>

<script>
import { getPlaceList, saveRangeList, getRangeList,getDelete } from '../../../api/renewalPlatformApi/index';

export default {
  name: '',
  props: {
    expandMapData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      manageComList: [],
      companyList: [],
      companyOpt: [],
      rangeForm: {
        manageCom: '',
        manageComCode: null,
        company: null,
      },
      dividerList: [],
      currentIsShowSonIdx: null,
      policyMapList: [],
      // 区域绘制
      drawState: '1',
      polygonFather: null,
      polygon: null,
      drawSaveVisible: false,
      drawName: '',
      drawFlag: false,
      drawAutoVisible: false,
      drawNextVisible: false,
      drawNormalName: '',
      // 区域超出控制
      fatherPath: null,
      currentPosition: null,
      // 多个未划分行政区域的模块
      nullRangeList: []
    }
  },
  mounted() {
    this.rangeForm = {
      manageCom: this.expandMapData.companyName,
      manageComCode: this.expandMapData.companyCode,
      placeCode: this.expandMapData.placeCode,
      company: '',
    },
    this.getCompanyList();
    this.initReinsuranceMap();
    this.getRangeListFn();
  },
  methods: {
    // 行政区域列表
    getCompanyList() {
      this.companyList = [];
      getPlaceList({ parentCode: this.rangeForm.placeCode }).then((res) => {
        if (res.code === 200) {
          res.data.forEach(item => {
            this.companyOpt.push(item.placeCode);
            this.companyList.push({ label: item.placeName, value: item.placeCode });
          });
          console.log(this.companyList)
        }
      }).finally(() => {})
    },
    // 分单区域列表
    getRangeListFn() {
      getRangeList({ companyCode: this.rangeForm.manageComCode }).then(res => {
        if (res.code == 200) {
          this.policyMapList = res.data || [];
          this.saveRange()
        }
      })
    },
    /** 三级机构分单区域 **/
    // 删除分单区域
    delPolicyMap(index) {
      this.$confirm('是否确认删除?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          getDelete({id:index.areaId}).then( res =>{
            if (res.code == 200) {
              this.$message.success(res.data)
              this.getRangeListFn()
            }
          })
        })
        .catch(function () {})
    },
    // 初始化三级机构地图
    initReinsuranceMap() {
      this.map = null;
      let acCode = this.expandMapData.placeCode + '';
      console.log(acCode,"acCodeacCodeacCodeacCode");
      this.map = new AMap.Map("dividerMap", {
        center: [116.30946, 39.937629],
        zoom: 3
      });
      let polygons = [];
      //行政区划查询
      let opts = {
        subdistrict: 1,   // 返回下一级行政区
        showbiz: false  // 最后一级返回街道信息
      };
      let district = new AMap.DistrictSearch(opts);//注意：需要使用插件同步下发功能才能这样直接使用
      // 清除地图上所有覆盖物
      for (let i = 0, l = polygons.length; i < l; i++) {
        polygons[i].setMap(null);
      }
      district.setLevel('city'); // 行政区级别
      district.setExtensions('all');
      // 行政区查询：按照adcode进行查询可以保证数据返回的唯一性
      const _this = this;
      district.search(acCode, function (status, result) {
        if (status === 'complete') {
          let data = result.districtList[0];
          console.log(data,"datdtatdatdtadtatdatda");
          let bounds = data.boundaries;
          if (bounds) {
            for (let i = 0, l = bounds.length; i < l; i++) {
              let polygon = new AMap.Polygon({
                map: _this.map,
                strokeWeight: 1,
                strokeColor: '#0091ea',
                fillColor: '#80d8ff',
                fillOpacity: 0.2,
                path: bounds[i]
              });
              polygons.push(polygon);
            }
            _this.map.setFitView();//地图自适应
          }
        }
      });
    },
    // 确定范围
    saveRange() {
      if (this.rangeForm.company) {
        this.drawFlag = true;
        this.drawState = '1';
        this.initReinsuranceSubMap(this.rangeForm.company + '');
      } else {
        this.$message.error('请选择行政区域！');
      }
    },
    // 回显对应分单区域
    showNeedRange() {
      const _this = this;
      this.policyMapList.forEach(item => {
        if (item.placeCode == this.rangeForm.company) {
          let path = JSON.parse(item.pathList);
          console.log(path)
          let polygon = new AMap.Polygon({
            map: _this.map,
            fillOpacity: 0.6,
            path,
            zindex: 9999
          });
          let pos = [];
          path.forEach(item => {
            pos.push({ lat: item[1], lng: item[0] });
          })
          console.log(item.areaName,pos,"pospospospos",JSON.parse(item.pathList));
          _this.addTextFn(item.areaName, this.calculateCenter(pos))
          _this.map.setFitView();
        }
      });
    },
    // 显示行政区域模块
    initReinsuranceSubMap(adCode) {
      this.map = null;
      this.map = new AMap.Map("dividerMap", {
        center: [116.30946, 39.937629],
        zoom: 3
      });
      let polygons = [];
      //行政区划查询
      let opts = {
        subdistrict: 1,   // 返回下一级行政区
        showbiz: false  // 最后一级返回街道信息
      };
      let district = new AMap.DistrictSearch(opts);//注意：需要使用插件同步下发功能才能这样直接使用
      district.setLevel('district'); // 行政区级别
      district.setExtensions('all');

      // 行政区查询：按照adcode进行查询可以保证数据返回的唯一性
      const _this = this;
      district.search(adCode, function (status, result) {
        if (status === 'complete') {
          let data = result.districtList[0];
          _this.fatherPath = data.boundaries;
          if (_this.fatherPath) {
            for (let i = 0, l = _this.fatherPath.length; i < l; i++) {
              let polygon = new AMap.Polygon({
                map: _this.map,
                strokeWeight: 1,
                strokeColor: '#0091ea',
                fillColor: '#80d8ff',
                fillOpacity: 0.2,
                path: _this.fatherPath[i]
              });
              polygons.push(polygon);
            }
            _this.map.setFitView();//地图自适应
            // 回显对应分单区域
            _this.showNeedRange();
          }
        }
      });
    },
    // 判断是否超出区域：FATHER（父与子）、SON（子与子）
    computePolygonFn(polygon1_path, polygon2_path, type) {
      // 小圈是否在大圈内
      let isRingInRing = AMap.GeometryUtil.isRingInRing(polygon2_path,polygon1_path);
      // 两圈是否交叉
      // let doesRingRingIntersect = AMap.GeometryUtil.doesRingRingIntersect(polygon2_path, polygon1_path);
      let ringRingClip = AMap.GeometryUtil.ringRingClip(polygon2_path, polygon1_path);
      let ringArea = parseInt(AMap.GeometryUtil.ringArea(ringRingClip));
      if (type == 'FATHER') {
        if (isRingInRing)  {
          // 两圈关系：在大圈内
          return true;
        } else {
          return false;
        }
      } else if (type == 'SON') {
        if (ringArea == 0)  {
          return true;
        } else {
          return false;
        }
      }
      return false;
    },
    // 获取绘制区域的中心
    calculateCenter(lnglatarr) {
      console.log('lnglatarr: ', lnglatarr)
      let total = lnglatarr.length;
      let X = 0, Y = 0, Z = 0;
      lnglatarr.map((item) => {
        let lng = (item.lng * Math.PI) / 180;
        let lat = (item.lat * Math.PI) / 180;
        let x, y, z;
        x = Math.cos(lat) * Math.cos(lng);
        y = Math.cos(lat) * Math.sin(lng);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      });
      X = X / total;
      Y = Y / total;
      Z = Z / total;
      let Lng = Math.atan2(Y, X);
      let Hyp = Math.sqrt(X * X + Y * Y);
      let Lat = Math.atan2(Z, Hyp);
      return new AMap.LngLat((Lng * 180) / Math.PI, (Lat * 180) / Math.PI);
    },
    // 图形绘制
    drawStart() {
      const _this = this;
      this.drawState = '2';
      this.polyEditTemp = new AMap.PolygonEditor(this.map);
      this.polyEditTemp.open();
      //关闭多边形编辑polygonEditor.close()触发该方法；
      this.polyEditTemp.on('end', function(event) {
        // event.target 即为编辑后的多边形对象,event.target.getPath()得到编辑完成后的点数组
        let pointArr = event.target.getPath()
        _this.polygonPaths = []
        for (let i = 0; i < pointArr.length; i++) {
          _this.polygonPaths.push({ lat: pointArr[i].lat, lng: pointArr[i].lng })
        }
      })
    },
    drawCancel() {
      this.polyEditTemp.getTarget().setMap(null);
      this.polyEditTemp.removeAdsorbPolygons(this.polygon);
      this.polyEditTemp.setTarget();
      this.polyEditTemp.close();
      this.drawState = '1';
      // this.polygon = null;
      // this.polyEditTemp = null;
    },
    drawSave() {
      // 存储经纬度
      this.drawSaveVisible = true;
    },
    // 分单区域模块中心位置添加名称
    addTextFn(name, position) {
      this.currentPosition = position;
      let text = new AMap.Text({
        text: name,
        anchor:'center', // 设置文本标记锚点
        cursor:'pointer',
        angle:10,
        style:{
          'padding': '.75rem .25rem',
          'border-radius': '.25rem',
          'border-width': 0,
          'text-align': 'center',
          'font-size': '18px',
          'color': 'black',
          'background-color': '#fff0'
        },
        position
      });
      text.setMap(this.map);
    },
    // 保存分单区域
    saveDrawFn() {
      this.polyEditTemp.close();
      let flag1 = this.computePolygonFn(this.fatherPath, this.polyEditTemp.getTarget().getPath(), 'FATHER');
      let flag2 = true;
      for (let i = 0; i < this.policyMapList.length; i++) {
        flag2 = this.computePolygonFn(JSON.parse(this.policyMapList[i].pathList), this.polyEditTemp.getTarget().getPath(), 'SON');
        if (!flag2) break;
      }
      if (!flag1) {
        this.$message.error('绘制的分单区域不可超出确定分单范围，请重新描线。');
        this.polyEditTemp.open();
      } else if (!flag2) {
        this.$message.error('绘制的两个分单区域间不可有交叉部分，请重新描线。');
        this.polyEditTemp.open();
      } else  {
        this.addTextFn(this.drawName, this.calculateCenter(this.polygonPaths));
        // 保存分单区域
        let len = this.policyMapList.length;
        let temp = {
          number: len == 0 ? 1 : len,
          areaName: this.drawName,
          companyCode: this.rangeForm.manageComCode,
          placeCode: this.rangeForm.company,
          centerTitude: JSON.stringify(this.currentPosition),
          pathList: JSON.stringify(this.polyEditTemp.getTarget().getPath()),
        }
        saveRangeList(temp).then(res => {
          if (res.code == 200) {
            this.getRangeListFn();
          }
        });
        this.drawState = '1';
      }
      this.drawSaveVisible = false;
    },
    cancelDrawFn(idx) {
      if (idx === '1') {
        this.drawSaveVisible = false;
        this.drawName = null;
      } else if (idx === '2') {
        this.drawAutoVisible = false;
      } else if (idx === '3') {
        this.drawNextVisible = false;
        this.drawNormalName = null;
      }
    },
    // 下一步
    nextOperateFn() {
      // // 多个行政区域未划分
      // let opt = [];
      // this.policyMapList.forEach(item => {
      //   opt.push(item.placeCode);
      // })
      // let arr = opt.concat(this.companyOpt);
      // this.nullRangeList = arr.filter((value, i, brr) => {
      //   return brr.indexOf(value) === brr.lastIndexOf(value);
      // });
      // if (this.nullRangeList.length > 0) { 
      //   this.drawAutoVisible = true;
      // } else {
      // 已全部划分
      console.log('this.policyMapList' ,this.policyMapList);
      let singleObj = {
        manageCom: this.rangeForm.manageCom,
        policyMapList: this.policyMapList,
      }
      // this.$router.push({
      //   path: 'singleTaskConf',
      //   query: {
      //     singleObj: singleObj
      //   }
      // });
      this.$emit("changeTab", "3", this.expandMapData, singleObj)
      // }
    },
    goBack(){
      this.$emit('changeTab', '1');
    },
    // 没有划分区域自动生成一个分单区域
    drawNextFn() {},
  }
}
</script>

<style lang="scss" scoped>
.map-exchange-bg{
  display: flex;
  .page-title-bg{
    display: flex;
    align-items: center;
    justify-content: space-between;
    .page-title{
      display: flex;
      align-items: center;
      font-size: 18px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #2A2A2A;
      .title-icon{
        width: 6px;
        height: 20px;
        background-color: #082AFF;
      }
      span{
        margin: 0 10px;
      }
    }
    .page-title-operate{
      padding-left: 10px;
    }
  }
  .map-bg{
    width: 60%;
    position: relative;
    ::v-deep.el-card__body{
      padding: 0;
    }
    #dividerMap{
      width: 100%;
      height: calc(100vh - 150px);
    }
    .map-operate{
      display: flex;
      align-items: center;
      position: absolute;
      top: 20px;
      right: 20px;
      z-index: 10;
      padding: 10px;
      background-color: #fff;
      .map-operate-icon, .map-operate-del-icon, .map-operate-ok-icon{
        font-size: 22px;
        font-weight: bold;
        padding: 0 8px;
      }
      .map-operate-del-icon {
        color: red;
      }
      .map-operate-ok-icon {
        color: #67c23a;
      }
    }
  }
  .operate-bg{
    width: 39%;
    margin-left: 10px;
    .divide-bg{
      .divide-upload{
        padding: 0 0 10px 10px;
        span:nth-child(1){
          color: #818181;
        }
        span:nth-child(2){
          color: #CFCFCF;
        }
      }
      .upload-btn{
        display: inline-block;
        margin-left: 10px;
      }
    }
  }
  ::v-deep.el-card__header {
    border: 0;
  }
  ::v-deep.el-card__body{
    padding: 15px;
  }
}
.son-manage-com{
  .son-title{
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 10px;
    font-size: 14px;
    span:nth-child(1){
      color: gray;
    }
  }
  .son-com-list{
    width: 360px;
  }
}
</style>
